<template>
	<view class="content">
		<image @click="close" src="https://renovationcdn.jiachuangnet.com/cad/close.png"
			style="position:absolute;top:20rpx;right:20rpx;width:46rpx;height: 46rpx;">
			<view class="title">蓝牙连接</view>
			<!-- <button @click="initBluetooth">初始化蓝牙</button>
		<button @click="searchDevices">搜索设备</button> -->
			<view style="display: flex;justify-content: space-around;align-items: center;">
				<view class="btn" @click="initBluetooth">
					<view style="display: flex;justify-content: center;margin-top:47rpx;margin-bottom:22rpx;">
						<image src="https://renovationcdn.jiachuangnet.com/cad/init.png"
							style="width: 74rpx;height:74rpx;"></image>
					</view>
					<view style="font-size: 26rpx;color: #1e272e;font-weight: 500;text-align: center;">初始化蓝牙</view>
				</view>
				<view class="btn" @click="searchDevices">
					<view style="display: flex;justify-content: center;margin-top:47rpx;margin-bottom:22rpx;">
						<image src="https://renovationcdn.jiachuangnet.com/cad/search.png"
							style="width: 74rpx;height:74rpx;"></image>

					</view>
					<view style="font-size: 26rpx;color: #1e272e;font-weight: 500;text-align: center;">搜索蓝牙</view>
				</view>
			</view>

			<view class="list">
				<view>设备列表：</view>

				<view v-for="(item, index) in devicesList" :key="index" @click="connectDevice(item)">

					<view style="font-size: 24rpx;width: 100%;" v-if="item.name ==='T7'">
						蓝牙激光测距仪-T7
					</view>
				</view>
			</view>

			<view class="list">
				<view>服务列表：</view>
				<view style="width: 100%;" v-for="(service, sIndex) in servicesList" :key="sIndex"
					@click="getCharacteristics(service)">
					<view style="font-size: 24rpx;width: 100%;"
						v-if="service.uuid  =='0000FFB0-0000-1000-8000-00805F9B34FB'">{{ service.uuid }}</view>
				</view>
			</view>
			<view class="list">
				<view>特征列表：</view>
				<view v-for="(char, cIndex) in characteristicsList" :key="cIndex" @click="enableNotification(char)">
					<view v-if="char.uuid == '0000FFB2-0000-1000-8000-00805F9B34FB'"
						style="font-size: 24rpx;width:100%">{{ char.uuid }}</view>
				</view>
			</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				devicesList: [], // 设备列表
				servicesList: [], // 服务列表
				characteristicsList: [], // 特征列表
				connectedDeviceId: '', // 当前连接设备ID
				connectedServiceId: '',
				output: '' ,// 输出信息
				
			}
		},
		onHide() {
			this.disconnect();
		},
		methods: {
			close() {
				this.$emit('close', true)
			},
			// 初始化蓝牙
			initBluetooth() {
				uni.showLoading({
					title: '设备正在初始化!'
				})
				// {{ item.name }} - {{ item.deviceId }}
				// ({{ char.properties.notify ? '可通知' : '' }})
				uni.openBluetoothAdapter({
					success: () => {
						uni.$u.toast('蓝牙初始化完成!');
						uni.onBluetoothDeviceFound(this.foundDevice)
					},
					fail: (err) => {
						uni.showToast({
							title: '初始化失败!',
							icon: 'error'
						});

					},
					complete: (data) => {
						uni.hideLoading();
					}
				})
			},

			// 搜索设备
			searchDevices() {
				uni.showLoading({
					title: '设备搜索中!'
				})
				uni.startBluetoothDevicesDiscovery({
					success: () => {
						uni.$u.toast('蓝牙搜索完成!');
					},
					fail: (err) => {
						uni.showToast({
							title: '未找到蓝牙设备!',
							icon: 'error'
						});
					},
					complete: (data) => {
						uni.hideLoading();
					}
				})
			},

			// 发现设备回调
			foundDevice(devices) {
				if (devices.devices[0].name && !this.devicesList.some(item => item.deviceId === devices.devices[0]
						.deviceId)) {
					this.devicesList.push(devices.devices[0])
				}
			},

			// 连接设备
			connectDevice(device) {
				this.connectedDeviceId = device.deviceId
				uni.createBLEConnection({
					deviceId: device.deviceId,
					success: () => {
						this.output = '连接成功'
						// 增加2000ms延迟
						setTimeout(() => {
							this.getServices(device.deviceId);
						}, 2000);

					},
					fail: (err) => {
						this.output = '连接失败: ' + err.errMsg
					}
				})
			},

			// 获取服务
			getServices(deviceId) {
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						this.output = '获取服务失败: '; //+ JSON.stringify(res); 
						if (res.services.length === 0) {
							uni.showToast({
								title: '未发现服务',
								icon: 'none'
							})
							return
						}
						this.servicesList = res.services
					},
					fail: (err) => {
						this.output = '获取服务失败: ' + err.errMsg
					}
				})
			},

			// 获取特征值
			getCharacteristics(service) {
				this.connectedServiceId = service.uuid;
				uni.getBLEDeviceCharacteristics({
					deviceId: this.connectedDeviceId,
					serviceId: service.uuid,
					success: (res) => {
						this.characteristicsList = res.characteristics
					},
					fail: (err) => {
						this.output = '获取特征失败: ' + err.errMsg
					}
				})
			},

			// 启用通知
			enableNotification(char) {
				//获取char封装的内容
				// this.output = `${JSON.stringify(char)}\r\n`
				// for (const key in char.properties) {
				//     this.output +=`${key}: ${char.properties[key]}\r\n`;
				// }

				if (char.properties.notify) {
					this.$emit('notifyClose', true);
					uni.$u.toast('蓝牙连接成功!');
					this.output += `发送: ${this.connectedDeviceId}-----${this.connectedServiceId}--------${char.uuid}\r\n`
					uni.notifyBLECharacteristicValueChange({
						deviceId: this.connectedDeviceId,
						serviceId: this.connectedServiceId, //char.serviceId,
						characteristicId: char.uuid,
						state: true,
						success: () => {
							uni.onBLECharacteristicValueChange((res) => {
								// this.output = `收到数据: ${this.ab2hex(res.value)}\r\n`
								// this.output += `转成ASCII字符串：${this.ab2ascii(res.value)}`
								this.$emit('value', this.ab2ascii(res.value))
							})
						}
					})
				}
			},

			// 优化后的断开连接方法
			disconnect() {
				if (!this.connectedDeviceId) {
					uni.showToast({
						title: '当前未连接设备',
						icon: 'none'
					})
					return
				}

				// 1. 关闭蓝牙连接
				uni.closeBLEConnection({
					deviceId: this.connectedDeviceId,
					success: () => {
						// 2. 停止设备搜索
						uni.stopBluetoothDevicesDiscovery()
						// 3. 清空相关数据
						this.connectedDeviceId = ''
						this.servicesList = []
						this.characteristicsList = []
						this.output = '设备已断开'
						uni.showToast({
							title: '断开成功',
							icon: 'success'
						})
					},
					fail: (err) => {
						this.output = '断开失败: ' + err.errMsg
						uni.showToast({
							title: '断开失败',
							icon: 'none'
						})
					}
				})
			},

			// 清空列表
			clearList() {
				this.devicesList = []
				this.servicesList = []
				this.characteristicsList = []
				this.output = '列表已清空'
			},

			// ArrayBuffer转16进制
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					bit => ('00' + bit.toString(16)).slice(-2)
				)
				return hexArr.join('')
			},

			// ArrayBuffer转ASCII字符串
			ab2ascii(buffer) {
				// 创建Uint8Array视图读取二进制数据
				const uint8Array = new Uint8Array(buffer);

				// 使用Array.from转换并拼接字符
				return Array.from(uint8Array)
					.map(byte => {
						// 处理ASCII可打印字符（32-126）和控制字符
						if (byte >= 32 && byte <= 126) {
							return String.fromCharCode(byte);
						} else {
							//非打印字符转义不处理
							return ``;
							//return `\\x${byte.toString(16).padStart(2, '0')}`; // 非打印字符转义
						}
					})
					.join('');
			}
		},
		beforeDestroy() {
			uni.closeBluetoothAdapter()
		}
	}
</script>

<style>
	.content {
		background: url('https://renovationcdn.jiachuangnet.com/cad/boxBg.png');
		border-radius: 10rpx;
		background-size: cover;
		/* height: 800rpx; */
		padding: 50rpx 25rpx;
		padding-top: 0;
	}

	.list {
		width: calc(100% - 20px);
		margin: 23rpx 0;
		box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
		/* border: 1px solid #ccc; */
		padding: 32rpx 10px;
		background-color: white;
		border-radius: 20rpx;
	}


	.btn {
		width: 260rpx;
		height: 215rpx;
		background-color: white;
		border-radius: 20rpx;
		box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.1);
	}

	.title {
		font-size: 42rpx;
		color: white;
		font-weight: 700;
		padding: 50rpx;
		text-align: center;
	}
</style>